<?php
namespace weixin\Controller;
use Think\Controller;
use Think\Cache\Driver\Memcached;
class IndexController extends Controller {
	
	/**
	 * 新注册用户生成Api调用配置开启接口 
	 */
    public function index(){
		$uid = $_GET["uid"];
		if(empty($uid)) return false;
		$userData = M('wxapi')->where("wxuid={$uid}")->find();
		$roobtName = !empty($userData['roobt'])?$userData['roobt']:"微信机器人";
		$newWechat = $this->newWechat($userData);
		list($wechat,$api) = $newWechat;
		// 获取微信消息
        $msg = $wechat->serve();
		//	\Think\Log::record('$msg' . $msg , 'INFO');
		//消息入库
		if($msg){
			$message= json_decode(json_encode($msg),true);
			$message['muid'] = $uid;
			M('wxmessage')->add($message);
		}
		//内容匹配回复
		switch ($msg->MsgType){
			case "text":
				//文字匹配回复
				$keyWord = empty($msg->Content)?false:$msg->Content;
				if($keyWord){
					$replyContent = $this->getReplyContent($keyWord,$roobtName);
				}else{
					$replyContent = "【{$roobtName}】已接收" ;
				}
				$wechat->reply($replyContent);
				break;
			case "event":
				$Event = $wechat->get_Event();
				$reply = $this->replyEventMsg($Event,$roobtName,$api);
				if($reply){
					$wechat->reply($reply);
				}
				break;
			default:
				$wechat->reply("您发送的消息【{$roobtName}】已成功接收");
		}
}


	/**
	 * @param $userData 用户api信息
	 * @return array 返回api token
	 */
	public function newWechat($userData){
		$m = new \Memcache();
		$m ->addServer("127.0.0.1", 11211);

		// 开发者中心-配置项-服务器配置-EncodingAESKey(消息加解密密钥)
		$encodingAESKey = 'ZOZxsuICmY614EBn41YgkRYZdOiCLruwpNxzWjEduKT';
		$wechat = new \Gaoming13\WechatPhpSdk\Wechat(
			array(
				'appId' 			=> $userData['appid'],
				'token' 			=> 	$userData['wxtoken'],
				'encodingAESKey'    =>	$encodingAESKey //可选
			)
		);

		$api = new \Gaoming13\WechatPhpSdk\Api(
			array(
				'appId' 			=> $userData['appid'],
				'appSecret'			=> $userData['appsecret'],
				'get_access_token'  => function() use($m){
					//读取token
					return $m->get('wechat_token'.I("uid"));
				},
				'save_access_token' => function($token)  use($m){
					//缓存token
					$m->set('wechat_token'.I('uid'), $token, 0);
				}
			)
		);
		return array($wechat,$api);
	}



	/**
	 * 消息处理 返回回复内容
	 */
	public function getReplyContent($keyWord,$roobtName){
		//匹配消息回复 或 发布消息
		$poster = $this->isPostContent($keyWord);
		if($poster){
			$replyContent = $poster;
		}else{
			$replyContent = M('wxkeywords')->where("wxkeyword like '%{$keyWord}%'")->find();
			if(!$replyContent){
				$replyContent = "【{$roobtName}】已接收";
			}
		}
		return $replyContent;
	}

	/**
	 * 事件消息反馈
	 */
	public  function replyEventMsg($Event,$roobtName,$api){
		if($Event){
			if($Event['Event'] == 'subscribe'){
				//将关注消息事件写入数据库
				$openid = $Event['FromUserName'];
				//找找是否存在
				$WxUser = M("wxuser")->where("openid = '{$openid}'")->find();
				if(empty($WxUser)){				//如果不存在将用户记录数据库  同时查询用书数据 信息
					//查询用户个人信息
					list($err,$res) =$api->get_user_info($openid);
					if($res){
						$res = json_decode(json_encode($res),ture);
						$data = $res;
					}
					//获取openid 关注时间
					$data['openid']	 		 = $openid;
					$data['subscribe_time']  = $Event['CreateTime'];
					$data['uid']			 = I('uid');
					M("wxuser")->add($data);
					$reply($userApi['wxwelcome']);
				}else{
					$reply('欢迎再次关注本公众号');
				}
			}else if($Event['Event'] == 'unsubscribe'){
				//$openid = $Event['openid'];
				//删除用户
				//M("wxuser")->where("openid = '{$openid}'")->delete();
				$reply('您取消了关注，欢迎再次关注');
			}
		}else{
			$reply = $roobtName;
		}
		return $reply;
	}

	/**
	 * 判断是否是发布消息
	 */
	public function isPostContent($keyWord=null){
		preg_match('/^(fb|FB)/',$keyWord, $isPostType);
		if(!empty($isPostType)){
			$replay = "系统已知晓 你想要发布一条分类消息";
		}else{
			$replay = false;
		}
		return $replay;

	}
}

